<?php

require_once __DIR__ . '/../vendor/autoload.php';
 
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$exchange = "topic_logs";

try {
    $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest','/'); // 建立连接到RabbitMQ服务器
    $channel = $connection->channel(); // 建立通道

    $channel->exchange_declare($exchange,'topic', false, false, false); // 试探性声明一个交换机


    $routingKey = isset($argv[1]) && !empty($argv[1]) ? $argv[1] : 'anonymous.info'; // 获取routing_key,没有默认为'anonymous.info'

    $data = implode( " ", array_slice($argv, 2)); // 获取发送数据
    $data = empty($data) ?"hello world":$data;

    // if (empty($data)) throw new Exception('请输入消息'); // 没有传入消息提示错误

    $message = new AMQPMessage($data[0]); // 定义消息
    $channel->basic_publish($message, $exchange, $routingKey); // 生产消息
    echo "发送中...";
    $channel->close();// 关闭通道
    $connection->close();// 关闭连接
} catch (Exception $e) {
    die($e->getMessage());
}